package com.lsh.oauth2.service.impl;

import com.lsh.oauth2.entity.SysPermission;
import com.lsh.oauth2.entity.SysRole;
import com.lsh.oauth2.repository.SysPermissionRepository;
import com.lsh.oauth2.repository.SysRolePermissionRepository;
import com.lsh.oauth2.repository.SysRoleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/8/18 10:37 下午
 * @desc ：SpringSecurity授权
 */
@Slf4j
@Service
public class PermissionEvaluatorImpl implements PermissionEvaluator {

    @Autowired
    SysRoleRepository roleRepository;
    @Autowired
    SysPermissionRepository permissionRepository;
    @Autowired
    SysRolePermissionRepository rolePermissionRepository;

    /**
     *
     * @param authentication 认证过的信息
     * @param targetUrl 要访问的目标路径
     * @param targetPermission 要访问的目标路径需要的权限
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) {
        log.info("目标URI："+targetUrl);
        log.info("目标权限："+targetPermission);
        //User是org.springframework.security.core.userdetails.User，是Userdetails的实现类
        //获得loadUserByUsername()方法的结果，即UserDetailsService的认证信息
        User user = (User)authentication.getPrincipal();
        // 获得loadUserByUsername()中注入的角色
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        ArrayList<Integer> roleIds = new ArrayList<>();
        // 遍历登录用户中所有角色
        authorities.forEach(authority ->{
            //获得角色Name
            String roleName = authority.getAuthority();
            SysRole role = roleRepository.findTopByName(roleName);
            roleIds.add(role.getId());

        });
        //通过RoleIDs 查询角色-权限关联表 返回权限Id 集合
        List<Integer> permissionIds = rolePermissionRepository.findPermissionIdByRoleIds(roleIds);
        //该用户所有的角色对应的权限集
        List<SysPermission> sysPermissionsByIdIn = permissionRepository.findSysPermissionsByIdIn(permissionIds);
        for (SysPermission sysPermission : sysPermissionsByIdIn) {
            log.info("当前权限："+sysPermission.getUrl()+", "+sysPermission.getPermission());
            if (targetUrl.equals(sysPermission.getUrl()) && targetPermission.equals(sysPermission.getPermission())){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String targetType, Object permission) {
        return false;
    }
}
